package it.fuesi.synoutils.services.tasks.filestation;

import android.app.Activity;
import android.content.Context;

import it.fuesi.synoutils.activities.FileStationFileDetailActivity;
import it.fuesi.synoutils.activities.MainActivity;
import it.fuesi.synoutils.fragments.FileStationFragment;
import it.fuesi.synoutils.helpers.FormatHelper;
import it.fuesi.synoutils.model.base.VoidDataObject;
import it.fuesi.synoutils.model.base.VoidResponse;
import it.fuesi.synoutils.model.filestation.FileStationClientParameters;
import it.fuesi.synoutils.services.cache.CacheService;
import it.fuesi.synoutils.services.client.FileStationClient;
import it.fuesi.synoutils.services.client.ServiceClientFactory;
import it.fuesi.synoutils.services.tasks.base.BaseTask;

/**
 * Created by pascotto on 17/10/14.
 */
public class DeleteFile extends BaseTask<VoidResponse, VoidDataObject, FileStationClientParameters> {

    private static final String TAG = DeleteFile.class.getName();

    public DeleteFile(Context context){
        super(context);
    }

    private FileStationClientParameters params;


    @Override
    protected String getCacheKey() {
        return null;
    }

    @Override
    public VoidResponse run(FileStationClientParameters params)  throws Exception{
            this.params = params;

            String path = "";

            if(params.getFilePathList() != null){
                for(String file : params.getFilePathList()){
                    path += FormatHelper.urlEncode(file) + ",";
                }
                path = path.substring(0, path.length()-1);

                publishProgress("Deleting " + params.getFilePathList().size() + " files");

            }else {
                publishProgress("Deleting file");
                path = FormatHelper.urlEncode(params.getFile_path());
            }

            FileStationClient client = ServiceClientFactory.getClient(FileStationClient.class);

            return client.deleteFile(path);
    }

    @Override
    protected void onPostExecute(VoidResponse voidResponse) {
        super.onPostExecute(voidResponse);

        if(voidResponse != null && voidResponse.isSuccess()){
            CacheService.expireCache(getContext(), FileStationList.CACHE_KEY_PREFIX + params.getFolder_path());
            if(getContext().getClass().equals(FileStationFileDetailActivity.class)) {
                FileStationFileDetailActivity activity = (FileStationFileDetailActivity) getContext();
                activity.setResult(Activity.RESULT_OK);
                activity.finish();
            }else{
                MainActivity activity = (MainActivity) getContext();
                FileStationFragment frag = (FileStationFragment)activity.getCurrentFragment();
                frag.doneDeleting(true);
            }
        }
    }
}
